/*
 * @copyright Copyright (c) 2010 Laboratório de Educação Cerebral. (http://www.educacaocerebral.com.br)
 *
 * This file is part of SoftVFC.
 *
 * SoftVFC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SoftVFC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SoftVFC.  If not, see <http://www.gnu.org/licenses/>.
 *
 * *********************
 *
 * Este arquivo é parte do programa SoftVFC.
 *
 * SoftVFC é um software livre; você pode redistribui-lo e/ou
 * modifica-lo dentro dos termos da Licença Pública Geral GNU como
 * publicada pela Fundação do Software Livre (FSF); na versão 3 da
 * Licença.
 *
 * Este programa é distribuido na esperança que possa ser util,
 * mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
 * MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
 * Licença Pública Geral GNU para maiores detalhes.
 *
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU
 * junto com este programa, se não, acesse no website oficial:
 * http://www.gnu.org/licenses/gpl.html
 *
 */
package org.softvfc.tablehandler.window;

import java.io.File;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.table.TableModel;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.softvfc.tablehandler.file.TableExporter;
import org.softvfc.tablehandler.file.TableImpoterDialog;

/**
 *
 * @author Diego Schmaedech Martins (schmaedech@gmail.com)
 * @version 29/07/2010
 */
@ConvertAsProperties(dtd = "-//org.softvfc.tablehandler.window//Table//EN",
autostore = false)
public final class TableTopComponent extends TopComponent {

    private static TableTopComponent instance;
    private static int count = 0;
    private final int index;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/softvfc/tablehandler/window/stock_data-new-table.png";
    private static final String PREFERRED_ID = "TableTopComponent";
 
    public TableTopComponent() {
        index = count++;
        initComponents();
        setName(NbBundle.getMessage(TableTopComponent.class, "CTL_TableTopComponent"));
        setToolTipText(NbBundle.getMessage(TableTopComponent.class, "HINT_TableTopComponent"));
        setIcon(ImageUtilities.loadImage(ICON_PATH, true));

    }

    public void changeTableModel(TableModel tableModel){
        jtTable.setModel(tableModel);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jbSaveAs = new javax.swing.JButton();
        jbOpenTable = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtTable = new javax.swing.JTable();

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jbSaveAs.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/softvfc/tablehandler/window/document-save-as.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jbSaveAs, org.openide.util.NbBundle.getMessage(TableTopComponent.class, "TableTopComponent.jbSaveAs.text")); // NOI18N
        jbSaveAs.setToolTipText(org.openide.util.NbBundle.getMessage(TableTopComponent.class, "TableTopComponent.jbSaveAs.toolTipText")); // NOI18N
        jbSaveAs.setFocusable(false);
        jbSaveAs.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbSaveAs.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSaveAsActionPerformed(evt);
            }
        });
        jToolBar1.add(jbSaveAs);

        jbOpenTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/softvfc/tablehandler/window/document-open.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(jbOpenTable, org.openide.util.NbBundle.getMessage(TableTopComponent.class, "TableTopComponent.jbOpenTable.text")); // NOI18N
        jbOpenTable.setToolTipText(org.openide.util.NbBundle.getMessage(TableTopComponent.class, "TableTopComponent.jbOpenTable.toolTipText")); // NOI18N
        jbOpenTable.setFocusable(false);
        jbOpenTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbOpenTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbOpenTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbOpenTableActionPerformed(evt);
            }
        });
        jToolBar1.add(jbOpenTable);

        jtTable.setAutoCreateRowSorter(true);
        jtTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jtTable.setColumnSelectionAllowed(true);
        jtTable.setFillsViewportHeight(true);
        jScrollPane1.setViewportView(jtTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 666, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 666, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jbSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSaveAsActionPerformed
        File file = null;
        TableExporter exp = new TableExporter();
        JFileChooser fileSave = new JFileChooser(System.getProperty("user.dir"));

        fileSave.setDialogType(JFileChooser.SAVE_DIALOG);
        int ret = fileSave.showDialog(this, "Save");

        if (ret == JFileChooser.APPROVE_OPTION) {
            file = fileSave.getSelectedFile();
            exp.exportTable( jtTable.getModel(),file);
            
        }
    }//GEN-LAST:event_jbSaveAsActionPerformed

    private void jbOpenTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbOpenTableActionPerformed

        File file = null;
        JFileChooser fileOpen = new JFileChooser(System.getProperty("user.dir"));
        fileOpen.setDialogType(JFileChooser.OPEN_DIALOG);
        int ret = fileOpen.showDialog(this, "Open");
        if (ret == JFileChooser.APPROVE_OPTION) {
            file = fileOpen.getSelectedFile();
            TableImpoterDialog dialog = new TableImpoterDialog(new javax.swing.JFrame(), true, file);
            dialog.setIconImage(ImageUtilities.loadImage(ICON_PATH, true));
            dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true); 
            if(dialog.isReady()){
                jtTable.setModel(dialog.getJtPreviewTable().getModel());
                setDisplayName("Table "+ file.getName()+" "+getIndex());
                requestActive();
            }else{
                JOptionPane.showMessageDialog(this, "No file was imported!","Message",  JOptionPane.INFORMATION_MESSAGE);
                
            }

        }
    }//GEN-LAST:event_jbOpenTableActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton jbOpenTable;
    private javax.swing.JButton jbSaveAs;
    private javax.swing.JTable jtTable;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized TableTopComponent getDefault() {
        if (instance == null) {
            instance = new TableTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the TableTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized TableTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(TableTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof TableTopComponent) {
            return (TableTopComponent) win;
        }
        Logger.getLogger(TableTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {

    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    /**
     * @return the index
     */
    public int getIndex() {
        return index;
    }
}
